package cn.gok.homework;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Book {
    private int bid;
    private String name;
    private float price;

    public Book(int bid, String name, float price) {
        this.bid = bid;
        this.name = name;
        this.price = price;
    }

    public void sell() {
        System.out.println("本书被卖了");
    }

    private void sell(float price, String name) {
        System.out.println("本书卖给了" + name + "，卖了" + price + "元");
    }

    public int getBid() {
        return bid;
    }

    public void setBid(int bid) {
        this.bid = bid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bid=" + bid +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        //基于反射技术，实现变量访问和方法调用
        Class bookClass = Book.class;
//        1 获取Book类信息，并获取全属性构造函数对象constructor
        Constructor constructor = bookClass.getConstructor(int.class, String.class, float.class);
//        2 利用该构造对象，创建1个书的实例。
        Book book = (Book) constructor.newInstance(1, "book", 1.1f);
//        3 通过反射，分别获取两个sell方法对应的method对象，并破坏封装性，分别调用该方法。
        Method method1 = bookClass.getDeclaredMethod("sell");
        Method method2 = bookClass.getDeclaredMethod("sell", float.class, String.class);
        method1.setAccessible(true);
        method1.invoke(book);
        method2.setAccessible(true);
        method2.invoke(book,book.getPrice(),"邱津芳");
    }
}
